import os
from django.http import HttpResponse, JsonResponse, FileResponse
from django.conf import settings
from django.views import View
from utils.response import ReturnCode, CommonResponseMixin
import hashlib


class ImageView(View, CommonResponseMixin):
    def get(self, request):
        md5 = request.GET.get("md5")
        img_file = os.path.join(settings.IMAGE_RESOURCE_DIR, md5 + ".jpg")
        if not os.path.exists(img_file):
            return HttpResponse("img file  not found!")
        else:
            return FileResponse(open(img_file, "rb"), content_type="image/jpeg")

    def post(self, request):
        files = request.FILES
        response_data = []
        for key, uploaded_file in files.items():
            print(key)
            print(uploaded_file)
            content = uploaded_file.read()
            md5 = hashlib.md5(content).hexdigest()
            path = os.path.join(settings.IMAGE_RESOURCE_DIR, md5 + '.jpg')
            print(md5)
            with open(path, 'wb+') as f:
                f.write(content)
            response_data.append({
                'name': key,
                'md5': md5
            })
        response = self.wrap_json_response(data=response_data, code=ReturnCode.SUCCESS)
        return JsonResponse(data=response, safe=False)

    def delete(self, request):
        md5 = request.GET.get("md5")
        img_file = os.path.join(settings.IMAGE_RESOURCE_DIR, md5 + ".jpg")
        if not os.path.exists(img_file):
            return HttpResponse("img file not found!")
        else:
            os.remove(img_file)
            return JsonResponse(data=self.wrap_json_response(message="delete success"), safe=False, status=200)


class ImageTextView(View, CommonResponseMixin):
    def get(self, request):
        md5 = request.GET.get("md5")
        img_file = os.path.join(settings.IMAGE_RESOURCE_DIR, md5 + ".jpeg")
        if not os.path.exists(img_file):
            return HttpResponse("img file not found!")
        else:
            response_data = dict(name=md5+".jpg", url=f"/services/image?md5={md5}")
            return JsonResponse(data=self.wrap_json_response(response_data), safe=False)


class ImageListView(View, CommonResponseMixin):
    def get(self, request):
        image_files = os.listdir(settings.IMAGE_RESOURCE_DIR)
        response_data = []
        for image_file in image_files:
            response_data.append(
                {
                    "name": image_file,
                    "md5": image_file[:-4]
                }
            )
        response_data = self.wrap_json_response(data=response_data)
        return JsonResponse(data=response_data)

